package com.enqualcomm.kids.mvp.voiceschedule;


import com.android.volley.VolleyError;
import com.android.volley.socket.ServerAddress;
import com.android.volley.socket.SocketAddressSwitcher;
import com.android.volley.socket.SocketStack;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.bean.VoiceSchedule;
import com.enqualcomm.kids.component.MyApplication;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.DeleteVoiceScheduleParams;
import com.enqualcomm.kids.network.socket.request.VoiceScheduleListParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.VoiceScheduleListResult;

import org.json.JSONObject;

import java.io.File;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import common.utils.MyLogger;
import de.greenrobot.event.EventBus;
import okio.Okio;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.BehaviorSubject;

/**
 * Created by yinzhiqun on 2016/3/10.
 *
 */
public class VoiceScheduleModel extends NetworkModel{


    private final BehaviorSubject<List<VoiceSchedule>> behaviorSubject;
    private final String terminalid;
    private final String userid;
    private final String userkey;
    ArrayList<VoiceSchedule> voiceSchedules;

    public VoiceScheduleModel(String terminalid) {
        this.terminalid = terminalid;
        AppDefault appDefault = new AppDefault();
        this.userid = appDefault.getUserid();
        this.userkey = appDefault.getUserkey();
        this.behaviorSubject = BehaviorSubject.create();
        EventBus eventBus = EventBus.getDefault();
        if (!eventBus.isRegistered(this)) {
            eventBus.register(this);
        }
        refresh();
    }

    public void onEvent(StringMessage message) {
        switch (message.msg) {
            case StringMessage.ADD_VOICE_SCHEDULE:
                refresh();
                break;
        }
    }

    public Observable<List<VoiceSchedule>> getVoiceSchedule(){
        return behaviorSubject.asObservable();
    }

    public void destroy() {
        onStop();
        EventBus.getDefault().unregister(this);
        behaviorSubject.onCompleted();
    }


    private void refresh() {
        //查询
        loadDataFromServer(new SocketRequest<VoiceScheduleListResult>(new VoiceScheduleListParams(userid, userkey, terminalid),
                new NetworkListener<VoiceScheduleListResult>() {
                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onSuccess(VoiceScheduleListResult response) {
                        if (response.code==0){
                            voiceSchedules = new ArrayList<>();
                            for (int i = 0; i < response.result.size(); i++) {
                                VoiceScheduleListResult.Result result = response.result.get(i);

                                String datetime = result.warnTime.substring(0, result.warnTime.length() - 3);
                                voiceSchedules.add(new VoiceSchedule(datetime,result.warnContent,result.id));
                            }

                            behaviorSubject.onNext(voiceSchedules);
                        }
                    }
                }));
    }

    volatile boolean isRunning;

    public void clear(){
        if (isRunning){
            return;
        }

        //清空数据
        if (voiceSchedules!=null&&voiceSchedules.size()!=0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0,size = voiceSchedules.size(); i <size ; i++) {
                stringBuilder.append(voiceSchedules.get(i).id).append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            sendDeleteCmd(stringBuilder.toString());
        }
    }

    public void delete(String id){
        if (isRunning){
            return;
        }

        sendDeleteCmd(id);
    }

    private void sendDeleteCmd(final String id) {
        isRunning = true;
        loadDataFromServer(new SocketRequest<BasicResult>(new DeleteVoiceScheduleParams(userid, userkey, terminalid,id),
                new NetworkListener<BasicResult>() {
                    @Override
                    public void onError(VolleyError error) {
                        isRunning = false;
                    }

                    @Override
                    public void onSuccess(BasicResult response) {
                        isRunning = false;
                        if (response.code == 0) {
                            if (voiceSchedules==null||voiceSchedules.isEmpty()) {
                                behaviorSubject.onNext(null);
                            }else{
                                ArrayList<VoiceSchedule> voiceSchedulesCopy = new ArrayList<>();
                                for (VoiceSchedule voiceSchedule : voiceSchedules) {
                                    int i = id.indexOf(voiceSchedule.id);
                                    if (i == -1){//删除的不是这一个
                                        voiceSchedulesCopy.add(voiceSchedule);
                                    }
                                }

                                voiceSchedules = voiceSchedulesCopy;
                                behaviorSubject.onNext(voiceSchedules);
                            }
                        }
                    }
                }));
    }


    public static final String OUT_OF_LIMIT = "OUT_OF_LIMIT";

    public static Observable<String> sendVoiceSchedule(final VoiceSchedule voiceSchedule,final String terminalid,final String relation){
        AppDefault appDefault = new AppDefault();
        final String userid = appDefault.getUserid();
        final String userkey = appDefault.getUserkey();

        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                ServerAddress serverAddress = new SocketAddressSwitcher(MyApplication.getInstance().getFilesDir() + "/server_config").getServerAddress();
                try {
                    String jsonStr = new JSONObject().put("userkey", userkey).put("userid", userid).put("relation",relation)
                            .put("terminalid", terminalid).put("time", voiceSchedule.datetime+":00").put("warnContent",voiceSchedule.content)
                            .toString();
//                    MyLogger.jLog().i(jsonStr);

                    byte[] jsonBuffer = jsonStr.getBytes();
                    File audio = new File(voiceSchedule.filePath);//音频文件
                    int fileLength = (int) audio.length();
                    int totalLength = 5 + jsonBuffer.length + fileLength;//发送内容总长度
                    byte[] totalBuffer = new byte[totalLength];

                    byte[] jsonLengthBuffer = com.android.volley.socket.IOUtil.wrapInt(jsonBuffer.length);//json长度

//                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//                    FileInputStream fileInputStream = new FileInputStream(audio);
//                    byte[] bytes = new byte[1024 * 4];
//                    int readLeng = 0;
//                    while ((readLeng = fileInputStream.read(bytes))!=-1){
//                        byteArrayOutputStream.write(bytes,0,readLeng);
//                    }
//                    byte[] filebuffer = byteArrayOutputStream.toByteArray();
//                    fileInputStream.close();

                    byte[] filebuffer =Okio.buffer(Okio.source(audio)).readByteArray();

                    totalBuffer[0] = 8;
                    System.arraycopy(jsonLengthBuffer, 0, totalBuffer, 1, 4);
                    System.arraycopy(jsonBuffer, 0, totalBuffer, 5, jsonBuffer.length);
                    System.arraycopy(filebuffer, 0, totalBuffer, 5 + jsonBuffer.length, fileLength);

                    Socket socket = new Socket(serverAddress.ip, 11647);
//                    Socket socket = new Socket("192.168.1.199", 8080);
                    socket.setSoTimeout(15 * 1000);
                    SocketStack.send(socket, totalBuffer);
                    byte[] receivedBytes = SocketStack.receive(socket);
                    SocketStack.closeSocket(socket);

                    if (receivedBytes[0]==4){//发送成功
                        subscriber.onNext(new String(receivedBytes,1,receivedBytes.length-1));
                    }else if (receivedBytes[0]==5){//"数量超出"
                        subscriber.onNext(OUT_OF_LIMIT);
                    }else{//"其他错误"
                        subscriber.onNext(null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onNext(null);
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

}
